/****************************************************************************
 *
 * MODULE:			   EndDevice with accelerometer (Arvatec) Project)
 *
 * VERSION:            2.5
 *
 * REVISION:           1.0
 *
 * DATED:              3/12/2007
 *
 * STATUS:            final release
 *
 * AUTHOR:             Allevi Ivan
 *
 * DESCRIPTION:
 *
 * Implements a Wireless Accelerometer Sensor End Device using the Jennic Zigbee stack.
 * Reads temperature, G value and battery voltage and transmits these to
 * network coordinator. Assumes code is running on Allix sensor board.
 *
 * LAST MODIFIED BY:   Allevi Ivan
 *                     3/12/2007
 *
 ****************************************************************************


/****************************************************************************/
/***        Include files                                                 ***/
/****************************************************************************/

#include <Utilities.h>

#include <jendefs.h>

#include "C:\Jennic\cygwin\jennic\SDK\Jenie\Include\jenie.h"
#include "C:\Jennic\cygwin\jennic\SDK\Jenie\Include\JPI.h"


#include <ALSdriver.h>
#include <HTSdriver.h>
#include <LedControl.h>
#include <AppHardwareApi.h>
#include <JZ_Api.h>
#include <gdb.h>
#include <sleep.h>
#include "Printf.h"

#include "WSN_Profile.h"


/****************************************************************************/
/***        Macro Definitions                                             ***/
/****************************************************************************/
/* Timing values */

#define APP_TICK_PERIOD_ms		  50
#define APP_TICK_PERIOD     	  (APP_TICK_PERIOD_ms * 32)

#define APP_DATA_SEND_PERIOD_ms	  1000
#define APP_DATA_SEND_PERIOD	  (APP_DATA_SEND_PERIOD_ms / APP_TICK_PERIOD_ms)
#define APP_SEND_ACK_PERIOD	  60*(APP_DATA_SEND_PERIOD_ms / APP_TICK_PERIOD_ms)
#define ONE_SEC_IN_32K_PERIODS 32000
#define APP_TIMEOUT_ACK_PERIOD      30*(APP_DATA_SEND_PERIOD_ms / APP_TICK_PERIOD_ms)

#define ADC_CHANNELS                4

#define PWM_CNT_H   0x8000
#define PWM_CNT_L   0x4000

/****************************************************************************/
/***        Type Definitions                                              ***/
/****************************************************************************/
typedef enum
{
	E_STATE_READ_ADC_IDLE,
	E_STATE_READ_ADC_CONVERTING,
	E_STATE_READ_ADC_COMPLETE,
    E_STATE_READ_ADC_READY
}teStateReadAdc;
/* Battery reading state definitions */
typedef enum
{
	E_STATE_POWER_OFF,
	E_STATE_FIRST_READ_COMPLETE,
	E_STATE_WAIT_BETWEEN_TWO_READS,
	E_STATE_SECOND_READ_COMPLETE,
	E_STATE_POWER_ON,
	E_STATE_IDLE
}teStateReadAccelerometer;

/* Battery reading state definitions */
typedef enum
{
	E_STATE_READ_BATT_VOLT_IDLE,
	E_STATE_READ_BATT_VOLTS_ADC_CONVERTING,
	E_STATE_READ_BATT_VOLTS_COMPLETE,
    E_STATE_READ_BATT_VOLTS_READY
}teStateReadBattVolt;

/* Temperature/Humidity Sensor - reading state definitions */
typedef enum
{
	E_STATE_READ_TEMP_HUMID_IDLE,
	E_STATE_READ_HUMID_RUNNING,
	E_STATE_READ_TEMP_HUMID_COMPLETE,
	E_STATE_READ_TEMP_START,
	E_STATE_READ_TEMP_HUMID_RUNNING,
	E_STATE_READ_TEMP_COMPLETE,
	E_STATE_READ_TEMP_HUMID_READY
}teStateReadTempHumidity;

/* Temperature/Humidity Sensor - reading state definitions */
typedef enum
{
E_STATE_READ_TEMP_VOLT_IDLE,
	E_STATE_READ_TEMP_VOLTS_ADC_CONVERTING,
	E_STATE_READ_TEMP_VOLTS_COMPLETE,
    E_STATE_READ_TEMP_VOLTS_READY

}teStateReadTemp;

/* Battery measurement data */
typedef struct
{
	uint16 					u16Reading;
	teStateReadBattVolt 	eState;
}tsBattSensor;

/* Battery measurement data */
typedef struct
{
	uint16 				u16Reading;
	teStateReadTemp 	eState;
}tsTemp;

/* Temp/Humidity measurement data */
typedef struct
{
	uint16 					u16TempReading;
	uint16 					u16HumidReading;
	teStateReadTempHumidity eState;
}tsTempHumiditySensor;

/* St accelerometer measurement data */
typedef struct
{
	int16 					u16XReading;
	int16 					u16YReading;
	int16 					u16ZReading;
	int16 					u16XReading2;
	int16 					u16YReading2;
	int16 					u16ZReading2;
	teStateReadAccelerometer eState;
}tsAccelerometerSensor;
/* ADC measurement data */
typedef struct
{
	uint16 					u16Reading;
	teStateReadAdc       	eState;
}tsAdc;
/****************************************************************************/
/***        Local Function Prototypes                                     ***/
/****************************************************************************/
PRIVATE void vInit(void);
PRIVATE void vSendData(void);
PRIVATE void vSendDataKvp();
PRIVATE void vInitSensors(void);
PRIVATE void vReadTempHumidity(void);
PRIVATE void vReadBatteryVoltage(void);
PRIVATE void vReadTemp(void);
PRIVATE void vAppTick(void *pvMsg, uint8 u8Param);
PRIVATE void readaccvalue(void);
PRIVATE void readaccvalue2(void);

PRIVATE void vAdc_Config(void);
PRIVATE void vAdc_ChangeChannel(void);
PRIVATE void vReadAdcVoltage(void);

PRIVATE tsAccelerometerSensor vGetAccDataFromFlash();
PRIVATE uint16 AbsV(int16 value);

PRIVATE void vTimerConfig(uint16 l, uint16 h);
PRIVATE void SET_PWM_DUTY(uint level);



/****************************************************************************/
/***        Local Variables                                               ***/
/****************************************************************************/
PRIVATE uint8 u8AppTicks = 0;
PRIVATE tsBattSensor sBattSensor;
PRIVATE tsTemp sTempSensor;

PRIVATE tsTempHumiditySensor sTempHumiditySensor;
PRIVATE tsAccelerometerSensor sAccelerometerSensor;
PRIVATE bool_t bAppTimerStarted = FALSE;
PRIVATE bool_t bNwkJoined = FALSE;
PRIVATE bool_t ReadState = FALSE;

PRIVATE uint8 u8IdDevice;
PRIVATE uint8 u8TypeDevice;

PRIVATE uint8 laccX=0;
PRIVATE uint8 haccX=0;
PRIVATE uint16 X=0;
PRIVATE uint8 laccY=0;
PRIVATE uint8 haccY=0;
PRIVATE uint16 Y=0;
PRIVATE uint8 laccZ=0;
PRIVATE uint8 haccZ=0;
PRIVATE uint16 Z=0;
PRIVATE  uint16 count=0;
PRIVATE uint8 au8AppData[6];
PRIVATE  int TimeM=2;

PRIVATE int8 Adc=-1;
PRIVATE tsAdc u16ADC1_Result[4];
PRIVATE uint8 port1=1;
PRIVATE uint8 port2=1;
PRIVATE uint8 port3=1;
PRIVATE uint16 timeout=0;
PRIVATE uint16 retry = 3; // numero tentativi per reset
PRIVATE uint16 countretry = 0; // contatore per tentativi di reset
PRIVATE uint16 sendackcount=0;
PRIVATE uint16 ack=0;
PRIVATE uint8 status_PWM=10;
PRIVATE uint8 old_status_PWM=10;

//PRIVATE uint16 test_pwm=0;
//PRIVATE uint8 s=0;




PRIVATE void vAdc_ChangeChannel(void)
{
            Adc++;
            if (Adc>=ADC_CHANNELS)
            {
                Adc=0;
            }
            vAHI_AdcEnable(E_AHI_ADC_SINGLE_SHOT,E_AHI_AP_INPUT_RANGE_1,Adc);
}
/****************************************************************************
 *
 * NAME: vAdc_Config
 *
 * DESCRIPTION:
 * configures ADC channel 1 2Vref
 *
 * PARAMETERS:      Name            RW  Usage
 * None.
 *
 * RETURNS:
 * None.
 *
 * NOTES:
 * None.
 ****************************************************************************/
void vAdc_Config(void)
{
  /* Enable ADC channel 1 to measure POT across power pins */
    vAHI_ApConfigure(E_AHI_AP_REGULATOR_ENABLE,
                     E_AHI_AP_INT_DISABLE,
                     E_AHI_AP_SAMPLE_8,
                     E_AHI_AP_CLOCKDIV_500KHZ,
                     E_AHI_AP_INTREF);
    while(bAHI_APRegulatorEnabled()==0);
    vAdc_ChangeChannel();
}
/****************************************************************************
 *
 * NAME: vReadBatteryVoltage
 *
 * DESCRIPTION:
 *
 * Uses ADC to read supply voltage. Measurement is performed using a state
 * machine to ensure that it never blocks.
 *
 ****************************************************************************/
PRIVATE void vReadAdcVoltage(void)
{
    uint16 u16AdcReading;

	switch(u16ADC1_Result[Adc].eState)
	{
		case E_STATE_READ_ADC_IDLE:
	    	vAHI_AdcStartSample();
	    	u16ADC1_Result[Adc].eState = E_STATE_READ_ADC_CONVERTING;
			break;

		case E_STATE_READ_ADC_CONVERTING:
	    	if (!bAHI_AdcPoll())
	    	{
	    	    u16ADC1_Result[Adc].eState = E_STATE_READ_ADC_COMPLETE;
	    	}
			break;

		case E_STATE_READ_ADC_COMPLETE:

		    u16ADC1_Result[Adc].u16Reading = u16AHI_AdcRead();

	    	u16ADC1_Result[Adc].eState = E_STATE_READ_ADC_READY;
			break;

		case E_STATE_READ_ADC_READY:
            vAdc_ChangeChannel();
			break;

		default:
			break;
	}
}
/*******************************
/****************************************************************************
 *
 * NAME: AppColdStart
 *
 * DESCRIPTION:
 * Entry point for application. Initialises system, starts scan then
 * processes interrupts.
 *
 * RETURNS:
 * void, never returns
 *
 ****************************************************************************/
PUBLIC void AppColdStart(void)
{
    	/* Debug hooks: include these regardless of whether debugging or not */
	HAL_GDB_INIT();
    HAL_BREAKPOINT();

    /* General initialisation: reset hardware */
    JZS_sConfig.u32Channel 	= WSN_CHANNEL;
    JZS_sConfig.u16PanId 	= WSN_PAN_ID;
    JZS_sConfig.bAutoJoin   = TRUE;
    //JZS_sConfig.bAutoPoll =0;

    //JZS_sConfig.pu8AppData = au8AppData;
    //JZS_sConfig.u16AppDataLength = 0;

    /* General initialisation: reset hardware */


    vInit();

    /* No return from the above function call */
}

/****************************************************************************
 *
 * NAME: AppWarmStart
 *
 * DESCRIPTION:
 * Entry point for application from boot loader. Simply jumps to AppColdStart
 * as, in this instance, application will never warm start.
 *
 * RETURNS:
 * Never returns.
 *
 ****************************************************************************/
PUBLIC void AppWarmStart(void)
{
    AppColdStart();
}

/****************************************************************************/
/***        Local Functions                                               ***/
/****************************************************************************/
/****************************************************************************
 *
 * NAME: vInit
 *
 * DESCRIPTION:
 * Initialises Zigbee stack and hardware. Final action is to start BOS, from
 * which there is no return. Subsequent application actions occur in the
 * functions defined above.
 *
 * RETURNS:
 * No return from thisGDB function
 *
 ****************************************************************************/
PRIVATE void vInit(void)
{
    /* Initialise Zigbee stack */
    JZS_u32InitSystem(TRUE);
    JZS_vStartStack();

    /* Set DIO for LEDs */
    //vLedInitRfd();
    //vLedControl(0,0);
    //vLedControl(1,0); /* Intialise serial comms unless debug mode*/

    vTimerConfig(0,0);




 vUART_printInit(E_AHI_UART_1,E_AHI_UART_RATE_19200,FALSE,E_AHI_UART_FIFO_LEVEL_1);

 vAHI_DioSetDirection(0, E_AHI_DIO0_INT);
 vAHI_DioSetDirection(0, E_AHI_DIO6_INT);
 vAHI_DioSetDirection(0, E_AHI_DIO14_INT);


//AR 14/04/2010
//vAHI_DioSetDirection(0,0x01);
//vAHI_DioSetDirection(0, (0x03 << 14));
//vAHI_DioSetDirection(0, (0x03 << 6));






  //vAHI_DioSetOutput(0,0x01);
vAHI_HighPowerModuleEnable(TRUE,TRUE);
    /* Set sensors */
    //vInitSensors();
vAdc_Config();  /* set adc config*/

    /* Start BOS */
    (void)bBosRun(TRUE);

    /* No return from the above function call */
}

/****************************************************************************
 *
 * NAME: vInitSensors
 *
 * DESCRIPTION:
 * Initialise the temperature/humidity sensor and set the ADC to measure the
 * supply voltage.
 *
 ****************************************************************************/
PRIVATE void vInitSensors(void)
{
    /* Initialise temp/humidity sensor interface */
    //vHTSreset();
    //sTempHumiditySensor.eState = E_STATE_READ_TEMP_HUMID_IDLE;

 /* Set wake timer for the next time that we want to read the sensors */
 vAHI_WakeTimerEnable(E_AHI_WAKE_TIMER_1, TRUE);

    /* Initialise ADC for internal battery voltage measurement */
	sBattSensor.eState = E_STATE_READ_BATT_VOLT_IDLE;

	vAHI_ApConfigure(E_AHI_AP_REGULATOR_ENABLE,
	                 E_AHI_AP_INT_DISABLE,
	                 E_AHI_AP_SAMPLE_2,
	                 E_AHI_AP_CLOCKDIV_2MHZ,
	                 E_AHI_AP_INTREF);

    /* Wait until the analogue peripheral regulator has come up before setting
       the ADC. */
    while(!bAHI_APRegulatorEnabled());

//init accelerometer state
    sAccelerometerSensor.eState = E_STATE_POWER_OFF;




int i=0;



}
PRIVATE uint16 AbsV(int16 value)
{
        if(value<0)
            {
                return (value*-1);
            }
                return (value);


}
/****************************************************************************
 *
 * NAME: vAppTick
 *
 * DESCRIPTION:
 *
 * Called by a BOS timer expiry. Reads sensor data and if complete transmits
 * to coordinator.
 *
 ****************************************************************************/
PRIVATE void vAppTick(void *pvMsg, uint8 u8Param)
{
    uint8 Channel=0;
    teStateReadAdc state=E_STATE_READ_ADC_READY;
    uint8 u8Msg;
    uint8 u8TimerId;
    static int resetp=0;
    static bool_t bToggle;

    uint16 DeltaX=100;
    uint16 DeltaY=100;
    uint16 DeltaZ=100;
   //vPrintf("\n\r tick event");
	/* Read sensor data */
//vReadTempHumidity();
	//vReadBatteryVoltage();
	//vReadTemp();
//ACCE DISABLE
	//accold=vGetAccDataFromFlash();
    //init spi
    int i=0;

  vAHI_HighPowerModuleEnable(TRUE,TRUE);

//vAHI_SpiConfigure( 1, /* number of slave selectlines in use */
//E_AHI_SPIM_MSB_FIRST, /* send data MScountretryB first */
//E_AHI_SPIM_RXPOS_EDGE, /* TX data to change onnegative edge */
//E_AHI_SPIM_RXPOS_EDGE, /* RX data to change onnegative edge */
//32, /* Generate 16MHz SPI clock */
//E_AHI_SPIM_INT_DISABLE, /* Disable SPI interrupt */
//E_AHI_SPIM_AUTOSLAVE_DSABL); /* Disable auto slave select*/
	//readaccvalue();
	//init accelerometer state
    sAccelerometerSensor.eState = E_STATE_POWER_OFF;

	/* Read sensor data */
	vReadAdcVoltage();
 //vPrintf(E_AHI_UART_1,"tick event\r\n");
 vPrintf(E_AHI_UART_1,"deviceid: %d - type: %d - port1: %d - port2: %d - port3: %d\r\n",u8IdDevice,u8TypeDevice,port1,port2,port3);


    if(port1==0)
    {
        vAHI_DioSetPullup(0, E_AHI_DIO0_INT);
        vAHI_DioSetOutput(E_AHI_DIO0_INT,0);
        //vAHI_DioSetPullup(0,0x01); // modifica pullup
        //vAHI_DioSetOutput(0x01,0);
    }
    else
    {
        vAHI_DioSetPullup(0, E_AHI_DIO0_INT);
        vAHI_DioSetOutput(0,E_AHI_DIO0_INT);
         //vAHI_DioSetPullup(0,0x01); // modifica pullup
         //vAHI_DioSetOutput(0,0x01);
    }

    if(port2==0)
    {
        vAHI_DioSetPullup(0, E_AHI_DIO14_INT);
        vAHI_DioSetOutput(E_AHI_DIO14_INT,0);
        //vAHI_DioSetPullup(0,(0x03 << 14)); // modifica pullup
        //vAHI_DioSetOutput((0x03 << 14),0);
    }
    else
    {
         //vAHI_DioSetPullup(0,(0x03 << 14)); // modifica pullup
         //vAHI_DioSetOutput(0,(0x03 << 14));
         vAHI_DioSetPullup(0, E_AHI_DIO14_INT);
         vAHI_DioSetOutput(0,E_AHI_DIO14_INT);

    }

    if(port3==0)
    {
        //port3
        vAHI_DioSetPullup(0, E_AHI_DIO6_INT);
        vAHI_DioSetOutput(E_AHI_DIO6_INT,0);
        //vAHI_DioSetPullup(0,(0x03 << 6)); // modifica pullup
        //vAHI_DioSetDirection((0x03 << 6),0);
    }
    else
    {
         //port3
         //vAHI_DioSetPullup(0,(0x03 << 6)); // modifica pullup
         //vAHI_DioSetDirection(0, (0x03 << 6));
         vAHI_DioSetPullup(0, E_AHI_DIO6_INT);
         vAHI_DioSetOutput(0,E_AHI_DIO6_INT);
    }

    if((port1==0)&&(port2==0)&&(port3==0))
    {
        status_PWM=0;
        if(old_status_PWM!=status_PWM)
        {
            SET_PWM_DUTY(0);
            old_status_PWM=status_PWM;
            vPrintf(E_AHI_UART_1,"Stato 000 set 0\r\n");
        }
    }
    else if((port1==1)&&(port2==1)&&(port3==1))
    {
        status_PWM=10;
        if(old_status_PWM!=status_PWM)
        {
            SET_PWM_DUTY(10);
            old_status_PWM=status_PWM;
            vPrintf(E_AHI_UART_1,"Stato 111 set 10\r\n");
        }
    }
     else if((port1==0)&&(port2==0)&&(port3==1))
    {
        status_PWM=3;
        if(old_status_PWM!=status_PWM)
        {
            SET_PWM_DUTY(3);
            old_status_PWM=status_PWM;
            vPrintf(E_AHI_UART_1,"Stato 110 set 3\r\n");
        }
    }
     else if((port1==0)&&(port2==1)&&(port3==0))
    {
        status_PWM=5;
        if(old_status_PWM!=status_PWM)
        {
            SET_PWM_DUTY(5);
            old_status_PWM=status_PWM;
            vPrintf(E_AHI_UART_1,"Stato 101 set 5\r\n");
        }
    }
    else if((port1==0)&&(port2==1)&&(port3==1))
    {
        status_PWM=7;
        if(old_status_PWM!=status_PWM)
        {
            SET_PWM_DUTY(7);
            old_status_PWM=status_PWM;
            vPrintf(E_AHI_UART_1,"Stato 101 set 7\r\n");
        }
    }


if(sendackcount>APP_SEND_ACK_PERIOD)
{
    sendackcount=0;
    //vPrintf(E_AHI_UART_1,"send ack message\r\n");
    ack=1;
    vSendDataKvp();
}
else
{
    sendackcount++;
}
if(ack==1)
{
    if (timeout > APP_TIMEOUT_ACK_PERIOD)
    {
        countretry++;

        if(countretry>retry)
        {
            //reset device
            //vPrintf(E_AHI_UART_1,"reset device after timeout ack \r\n");
           //AR vAHI_DioSetPullup(0,(0x01 << 6)); // modifica pullup
           //AR vAHI_DioSetDirection(0, (0x01 << 6));
        //AR vAHI_DioSetOutput(0, (0x01 << 6));

            vAHI_DioSetPullup(0, E_AHI_DIO6_INT);
            vAHI_DioSetDirection(0, E_AHI_DIO6_INT);
            vAHI_DioSetOutput(E_AHI_DIO6_INT,0);

            vAHI_DioSetPullup(0, E_AHI_DIO0_INT);
            vAHI_DioSetDirection(0, E_AHI_DIO0_INT);
            vAHI_DioSetOutput(E_AHI_DIO0_INT,0);

            vAHI_DioSetPullup(0, E_AHI_DIO14_INT);
            vAHI_DioSetDirection(0, E_AHI_DIO14_INT);
            vAHI_DioSetOutput(E_AHI_DIO14_INT,0);
            status_PWM=10;
            old_status_PWM=10;



            //conteggio reset + save flash
            bNwkJoined = FALSE;
            JZS_vStartStack();
        } else
        {
            ack=0;
            //vPrintf(E_AHI_UART_1,"Kvp Response Lost %d \r\n", countretry);
        }
        timeout = 0;
    }
    else
    {
        timeout++;
    }
}


if (u8AppTicks++ > APP_DATA_SEND_PERIOD)
	{
	     //vPrintf(E_AHI_UART_1,"end send period \r\n");
	    for(Channel=0;Channel<ADC_CHANNELS;Channel++)
	    {
                if(u16ADC1_Result[Channel].eState!=E_STATE_READ_ADC_READY)
                {
                    state=u16ADC1_Result[Channel].eState;
                    break;
                }
            state=E_STATE_READ_ADC_READY;
        }
	    /* If sensor reads are complete */
	    if (state == E_STATE_READ_ADC_READY)
        {
		    u8AppTicks = 0;
           // printf("$PFAL,TCP.Client.Send,49,\"DeviceName=8B1AA5C1-227A-40F7-9A5D-730CF8D75EA0$ExtData=1,1,%d,%d,%d,%d,0,0,0,0,0,0,0,0,0,0,0,0,00000000\"\r\n",u16ADC1_Result[0].u16Reading,
            //u16ADC1_Result[1].u16Reading,u16ADC1_Result[2].u16Reading,u16ADC1_Result[3].u16Reading);
            //instead of acc value i will use adc reads

             //ar modifica negare adc1
             u16ADC1_Result[0].u16Reading=4096-u16ADC1_Result[0].u16Reading;

            sAccelerometerSensor.u16XReading=u16ADC1_Result[0].u16Reading;

            sAccelerometerSensor.u16YReading=u16ADC1_Result[1].u16Reading;
            sAccelerometerSensor.u16ZReading=u16ADC1_Result[3].u16Reading;

            for(Channel=0;Channel<ADC_CHANNELS;Channel++)
            {
                u16ADC1_Result[Channel].eState = E_STATE_READ_ADC_IDLE;
            }
            //vPrintf(E_AHI_UART_1,"adc ready\r\n");
            //vPrintf(E_AHI_UART_1,"adc 0 : %d\r\n",sAccelerometerSensor.u16XReading);
            //vPrintf(E_AHI_UART_1,"adc 1 : %d\r\n",sAccelerometerSensor.u16YReading);
            //vPrintf(E_AHI_UART_1,"adc 2 : %d\r\n",sAccelerometerSensor.u16ZReading);
            if(bNwkJoined==TRUE)
            {
                    //vPrintf(E_AHI_UART_1,"send data\r\n");
                    vSendData();
            }
        }
	}

//	if(test_pwm>200)
//	{
//
//	     SET_PWM_DUTY((s++)%11 );
//	     test_pwm=0;
//
//
//	}
//	else
//	{
//	    test_pwm++;
//
//	}




            sBattSensor.eState = E_STATE_READ_BATT_VOLT_IDLE;
            sAccelerometerSensor.eState = E_STATE_POWER_OFF;


    (void)bBosCreateTimer(vAppTick, &u8Msg, 0, (APP_TICK_PERIOD_ms / 10), &u8TimerId);
}

/****************************************************************************
 *
 * NAME: vReadBatteryVoltage
 *E_AHI_UART_
 * DESCRIPTION:
 *
 * Uses ADC to read supply voltage. Measurement is performed using a state
 * machine to ensure that it never blocks.
 *
 ****************************************************************************/
PRIVATE void vReadBatteryVoltage(void)
{
    uint16 u16AdcReading;

	switch(sBattSensor.eState)
	{
		case E_STATE_READ_BATT_VOLT_IDLE:
                vAHI_AdcEnable(E_AHI_ADC_CONVERT_DISABLE,
                   E_AHI_AP_INPUT_RANGE_2,
                   E_AHI_ADC_SRC_VOLT);

	    	vAHI_AdcStartSample();
	    	sBattSensor.eState = E_STATE_READ_BATT_VOLTS_ADC_CONVERTING;
			break;

		case E_STATE_READ_BATT_VOLTS_ADC_CONVERTING:
	    	if (!bAHI_AdcPoll())
	    	{
	    	    sBattSensor.eState = E_STATE_READ_BATT_VOLTS_COMPLETE;
	    	}
			break;

		case E_STATE_READ_BATT_VOLTS_COMPLETE:

		    u16AdcReading = u16AHI_AdcRead();

		    /* Input range is 0 to 2.4V. ADC has full scale range of 12 bits.
		       Therefore a 1 bit change represents a voltage of approx 586uV */
		    sBattSensor.u16Reading = ((uint32)((uint32)(u16AdcReading * 586) +
                                     ((uint32)(u16AdcReading * 586) >> 1)))  /
                                     1000;

	    	sBattSensor.eState = E_STATE_READ_BATT_VOLTS_READY;
			break;

		case E_STATE_READ_BATT_VOLTS_READY:
			break;

		default:
			break;
	}
}

/****************************************************************************
 *
 * NAME: vReadTemp
 *
 * DESCRIPTION:
 *
 * Uses ADC to read supply voltage. Measurement is performed using a state
 * machine to ensure that it never blocks.
 *
 ****************************************************************************/
PRIVATE void vReadTemp(void)
{
    uint16 u16AdcReading;

	switch(sBattSensor.eState)
	{
		case E_STATE_READ_TEMP_VOLT_IDLE:
		    vAHI_AdcEnable(E_AHI_ADC_CONVERT_DISABLE,
                   E_AHI_AP_INPUT_RANGE_2,
                   E_AHI_ADC_SRC_TEMP);
	    	vAHI_AdcStartSample();
	    	sTempSensor.eState = E_STATE_READ_TEMP_VOLTS_ADC_CONVERTING;
			break;

		case E_STATE_READ_TEMP_VOLTS_ADC_CONVERTING:
	    	if (!bAHI_AdcPoll())
	    	{
	    	    sTempSensor.eState = E_STATE_READ_TEMP_VOLTS_COMPLETE;
	    	}
			break;

		case E_STATE_READ_TEMP_VOLTS_COMPLETE:

		    u16AdcReading = u16AHI_AdcRead();

		    /* Input range is 0 to 2.4V. ADC has full scale range of 12 bits.
		       Therefore a 1 bit change represents a voltage of approx 586uV */
		    sTempSensor.u16Reading = u16AdcReading;

	    	sTempSensor.eState = E_STATE_READ_TEMP_VOLTS_READY;
			break;

		case E_STATE_READ_TEMP_VOLTS_READY:
			break;

		default:
			break;
	}
}

/****************************************************************************
 *
 * NAME: vReadTempHumidity
 *
 * DESCRIPTION:
 *
 * Read temperature/humidity sensor. Reading is performed using a state machine
 * to ensure that it never blocks.
 *
 ****************************************************************************/
PRIVATE void vReadTempHumidity(void)
{
    switch(sTempHumiditySensor.eState)
	{
		case E_STATE_READ_TEMP_HUMID_IDLE:
		    vHTSstartReadHumidity();
			sTempHumiditySensor.eState = E_STATE_READ_HUMID_RUNNING;
		break;

		case E_STATE_READ_HUMID_RUNNING:
			if ((u32AHI_DioReadInput() & HTS_DATA_DIO_BIT_MASK) == 0)
			{
				sTempHumiditySensor.eState = E_STATE_READ_TEMP_HUMID_COMPLETE;
			}
			break;

		case E_STATE_READ_TEMP_HUMID_COMPLETE:
			sTempHumiditySensor.u16HumidReading = u16HTSreadHumidityResult();
			sTempHumiditySensor.eState     = E_STATE_READ_TEMP_START;
			break;

		case E_STATE_READ_TEMP_START:
		    vHTSstartReadTemp();
			sTempHumiditySensor.eState = E_STATE_READ_TEMP_HUMID_RUNNING;
			break;

		case E_STATE_READ_TEMP_HUMID_RUNNING:
			if ((u32AHI_DioReadInput() & HTS_DATA_DIO_BIT_MASK) == 0)
			{
				sTempHumiditySensor.eState = E_STATE_READ_TEMP_COMPLETE;
			}
			break;

		case E_STATE_READ_TEMP_COMPLETE:
			sTempHumiditySensor.u16TempReading = u16HTSreadTempResult();
			sTempHumiditySensor.eState     = E_STATE_READ_TEMP_HUMID_READY;
			break;

		case E_STATE_READ_TEMP_HUMID_READY:
			break;

		default:
			break;
	}
}

/****************************************************************************
 *
 * NAME: readaccvalue value
 *
 * DESCRIPTION:
 * read accelerometer value
 *
 ****************************************************************************/
PRIVATE void readaccvalue(void)
{

#define FLASHREADCMD 0x03
#define SPI_SLCT_NONE 0x00
uint8 u8Temp;
uint32 i;
uint8 in_byte;
uint16 register_name;


// up device
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2000;
register_name &= 0x7F00; //Set D7 to 0 for write mode
vAHI_SpiStartTransfer16(register_name);
vAHI_SpiWaitBusy();

vAHI_SpiStartTransfer8(0x47);
vAHI_SpiWaitBusy();

vAHI_SpiSelect(SPI_SLCT_NONE);
for(i=0;i<100000;i++);

/*
//g
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2100;
register_name &= 0x7F00; //Set D7 to 0 for write mode
vAHI_SpiStartTransfer16(register_name);
vAHI_SpiWaitBusy();
vAHI_SpiStartTransfer8(0xC0);
vAHI_SpiWaitBusy();
//vAHI_SpiStartTransfer8(0x00);
for(i=0;i<1000000;i++);
vAHI_SpiSelect(SPI_SLCT_NONE);
*/



//asse x
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2800;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
laccX=in_byte;


vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2900;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
haccX=in_byte;
X=haccX;
X= X<<8;
X|= laccX;
X&=0x0FFF;
sAccelerometerSensor.u16XReading=X;
if (X & 0x800)
{
X=~X;
X&=0x0FFF;
X++;
sAccelerometerSensor.u16XReading=(-1)*X;
}





//asse y
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2A00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
laccY=in_byte;


vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2B00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
haccY=in_byte;

Y=haccY;
Y= Y<<8;
Y|= laccY;
Y&=0x0FFF;
sAccelerometerSensor.u16YReading=Y;
if (Y & 0x800)
{
Y=~Y;
Y&=0x0FFF;
Y++;
sAccelerometerSensor.u16YReading=(-1)*Y;
}

// Z
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2C00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
laccZ=in_byte;


vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2D00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
haccZ=in_byte;

Z=haccZ;
Z= Z<<8;
Z|= laccZ;
Z&=0x0FFF;
sAccelerometerSensor.u16ZReading=Z;
if (Z & 0x800)
{
Z=~Z;
Z&=0x0FFF;
Z++;
sAccelerometerSensor.u16ZReading=(-1)*Z;
}


/*
//power down device
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2000;
register_name &= 0x7F00; //Set D7 to 0 for write mode
vAHI_SpiStartTransfer16(register_name);
vAHI_SpiWaitBusy();

vAHI_SpiStartTransfer8(0x87);
vAHI_SpiWaitBusy();
//vAHI_SpiStartTransfer8(0x00);

vAHI_SpiSelect(SPI_SLCT_NONE);
for(i=0;i<100000;i++);
*/





}

/****************************************************************************
 *
 * NAME: readaccvalue value
 *
 * DESCRIPTION:
 * read accelerometer value
 *
 ****************************************************************************/
PRIVATE void readaccvalue2(void)
{

#define FLASHREADCMD 0x03
#define SPI_SLCT_NONE 0x00
uint8 u8Temp;
uint32 i;
uint8 in_byte;
uint16 register_name;


//power up device
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2000;
register_name &= 0x7F00; //Set D7 to 0 for write mode
vAHI_SpiStartTransfer16(register_name);
vAHI_SpiWaitBusy();

vAHI_SpiStartTransfer8(0x47);
vAHI_SpiWaitBusy();

vAHI_SpiSelect(SPI_SLCT_NONE);
for(i=0;i<100000;i++);

/*
//g
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2100;
register_name &= 0x7F00; //Set D7 to 0 for write mode
vAHI_SpiStartTransfer16(register_name);
vAHI_SpiWaitBusy();
vAHI_SpiStartTransfer8(0xC0);
vAHI_SpiWaitBusy();
//vAHI_SpiStartTransfer8(0x00);
for(i=0;i<1000000;i++);
vAHI_SpiSelect(SPI_SLCT_NONE);
*/



//asse x
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2800;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
laccX=in_byte;


vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2900;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
haccX=in_byte;

X=haccX;
X= X<<8;
X|= laccX;
X&=0x0FFF;
sAccelerometerSensor.u16XReading2=X;
if (X & 0x800)
{
X=~X;
X&=0x0FFF;
X++;
sAccelerometerSensor.u16XReading2=(-1)*X;
}





//asse y
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2A00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
laccY=in_byte;


vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2B00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
haccY=in_byte;

Y=haccY;
Y= Y<<8;
Y|= laccY;
Y&=0x0FFF;
sAccelerometerSensor.u16YReading2=Y;
if (Y & 0x800)
{
Y=~Y;
Y&=0x0FFF;
Y++;
sAccelerometerSensor.u16YReading2=(-1)*Y;
}

// Z
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2C00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
laccZ=in_byte;


vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2D00;
register_name |= 0x8000; //Set D7 to 1 for read mode
vAHI_SpiStartTransfer16(register_name); //Read outx_l
vAHI_SpiWaitBusy();
in_byte = u8AHI_SpiReadTransfer8();
vAHI_SpiSelect(SPI_SLCT_NONE);
haccZ=in_byte;

Z=haccZ;
Z= Z<<8;
Z|= laccZ;
Z&=0x0FFF;
sAccelerometerSensor.u16ZReading2=Z;
if (Z & 0x800)
{
Z=~Z;
Z&=0x0FFF;
Z++;
sAccelerometerSensor.u16ZReading2=(-1)*Z;
}



//power down device
vAHI_SpiSelect(E_AHI_SPIM_SLAVE_ENBLE_1);
register_name=0x2000;
register_name &= 0x7F00; //Set D7 to 0 for write mode
vAHI_SpiStartTransfer16(register_name);
vAHI_SpiWaitBusy();

vAHI_SpiStartTransfer8(0x87);
vAHI_SpiWaitBusy();
//vAHI_SpiStartTransfer8(0x00);

vAHI_SpiSelect(SPI_SLCT_NONE);
for(i=0;i<100000;i++);






}



PRIVATE tsAccelerometerSensor vGetAccDataFromFlash()
{
        tsAccelerometerSensor TempAcc;
        uint16 Xold;
        uint16 Yold;
        uint16 Zold;

Xold=au8AppData[0];
Xold= Xold<<8;
Xold|= au8AppData[1];
Xold&=0x0FFF;
TempAcc.u16XReading=Xold;
if (Xold & 0x800)
{
Xold=~Xold;
Xold&=0x0FFF;
Xold++;
TempAcc.u16XReading=(-1)*Xold;
}



Yold=au8AppData[2];
Yold= Yold<<8;
Yold|= au8AppData[3];
Yold&=0x0FFF;
TempAcc.u16YReading=Yold;
if (Yold & 0x800)
{
Yold=~Yold;
Yold&=0x0FFF;
Yold++;
TempAcc.u16YReading=(-1)*Yold;
}

Zold=au8AppData[4];
Zold= Zold<<8;
Zold|= au8AppData[5];
Zold&=0x0FFF;
TempAcc.u16ZReading=Zold;
if (Zold & 0x800)
{
Zold=~Zold;
Zold&=0x0FFF;
Zold++;
TempAcc.u16ZReading=(-1)*Zold;
}

return (TempAcc);
}
/****************************************************************************
 *
 * NAME: vSendData
 *
 * DESCRIPTION:
 *
 * Transmit sensor data to coordinator.
 *
 ****************************************************************************/
PRIVATE void vSendDataKvp()
{
    static int i=0;
    static int t=0;
AF_Transaction_s asTransaction;
    asTransaction.uFrame.sKvp.u16AttributeID = 0x01;
    asTransaction.uFrame.sKvp.eErrorCode = KVP_SUCCESS;



    asTransaction.u8SequenceNum = u8AfGetTransactionSequence(TRUE);

    asTransaction.uFrame.sKvp.eCommandTypeID = SET_ACKNOWLEDGMENT;
    asTransaction.uFrame.sKvp.eAttributeDataType = KVP_CHARACTER_STRING;
memcpy(&asTransaction.uFrame.sKvp.uAttributeData.CharacterString.au8CharacterData,
					"A", 2);
asTransaction.uFrame.sKvp.uAttributeData.CharacterString.u8CharacterCount=2;

(void)afdeDataRequest(APS_ADDRMODE_SHORT,       /* Address type */
                          0x0000,                   /* Destination address */
                          WSN_DATA_SINK_ENDPOINT,   /* destination endpoint */
                          WSN_DATA_SOURCE_ENDPOINT, /* Source endpoint */
                          WSN_PROFILE_ID,           /* Profile ID */
                          WSN_CID_SENSOR_READINGS,  /* Cluster ID */
                          AF_KVP,                   /* Frame type */
                          1,                        /* Transactions */
                          &asTransaction,            /* Transaction data */
                          APS_TXOPTION_NONE,        /* Transmit options */
                          ENABLE_ROUTE_DISCOVERY, /* Route discovery mode */
                          0);                       /* Radius count */

                       /* Radius count */
                        //allevi ivan 21/07/2007 save stack state and enter in sleep mode
                        //vAppSaveContexts();
                       //vBosRequestSleep(FALSE);
}

/****************************************************************************
 *
 * NAME: vSendData
 *
 * DESCRIPTION:
 *
 * Transmit sensor data to coordinator.
 *
 ****************************************************************************/
PRIVATE void vSendData(void)
{
    AF_Transaction_s asTransaction[1];

    asTransaction[0].u8SequenceNum = u8AfGetTransactionSequence(TRUE);
    asTransaction[0].uFrame.sMsg.u8TransactionDataLen = 12;

    asTransaction[0].uFrame.sMsg.au8TransactionData[0] = port1;//sBattSensor.u16Reading;
	asTransaction[0].uFrame.sMsg.au8TransactionData[1] = port2;//sBattSensor.u16Reading >> 8;
    asTransaction[0].uFrame.sMsg.au8TransactionData[2] = sAccelerometerSensor.u16XReading;
	asTransaction[0].uFrame.sMsg.au8TransactionData[3] = sAccelerometerSensor.u16XReading >> 8;
    asTransaction[0].uFrame.sMsg.au8TransactionData[4] = sAccelerometerSensor.u16YReading;
	asTransaction[0].uFrame.sMsg.au8TransactionData[5] = sAccelerometerSensor.u16YReading >> 8;
	asTransaction[0].uFrame.sMsg.au8TransactionData[6] = sAccelerometerSensor.u16ZReading;
	asTransaction[0].uFrame.sMsg.au8TransactionData[7] = sAccelerometerSensor.u16ZReading >> 8;
	asTransaction[0].uFrame.sMsg.au8TransactionData[8] = 0;//sTempSensor.u16Reading;
	asTransaction[0].uFrame.sMsg.au8TransactionData[9] = port3;//sTempSensor.u16Reading >> 8;
	asTransaction[0].uFrame.sMsg.au8TransactionData[10] = 10; //state value
	asTransaction[0].uFrame.sMsg.au8TransactionData[11] = 3;


(void)afdeDataRequest(APS_ADDRMODE_SHORT,       /* Address type */
                          0x0000,                   /* Destination address */
                          WSN_DATA_SINK_ENDPOINT,   /* destination endpoint */
                          WSN_DATA_SOURCE_ENDPOINT, /* Source endpoint */
                          WSN_PROFILE_ID,           /* Profile ID */
                          WSN_CID_SENSOR_READINGS,  /* Cluster ID */
                          AF_MSG,                   /* Frame type */
                          1,                        /* Transactions */
                          asTransaction,            /* Transaction data */
                          APS_TXOPTION_NONE,        /* Transmit options */
                          ENABLE_ROUTE_DISCOVERY, /* Route discovery mode */
                          0);                       /* Radius count */


                       /* Radius count */
                        //allevi ivan 21/07/2007 save stack state and enter in sleep mode
                        //vAppSaveContexts();
                       //vBosRequestSleep(FALSE);
}

/****************************************************************************/
/***               Functions called by the stack                          ***/
/****************************************************************************/

/****************************************************************************
 *
 * NAME: JZA_vZdpResponse
 *
 * DESCRIPTION:
 * Called when a ZDP response frame has been received. In this application no
 * action is taken as no ZDP responses are anticipated.
 *
 * PARAMETERS:      Name           RW  Usage
 *                  u8Type         R   ZDP response type
 *                  pu8Payload     R   Payload buffer
 *                  u8PayloadLen   R   Length of payload
 *
 ****************************************************************************/
PUBLIC void JZA_vZdpResponse(uint8  u8Type,
                             uint8  u8LQI,
                             uint8 *pu8Payload,
                             uint8  u8PayloadLen)

{
}

/****************************************************************************
 *
 * NAME: JZA_pu8AfMsgObject
 *
 * DESCRIPTION:
 * Called when a MSG transaction has been received with a matching endpoint.
 *
 * PARAMETERS:      Name           RW  Usage
 *                  afSrcAddr      R   Address of sender device
 *                  dstEndPoint    R   Endpoint at receiver
 *                  clusterID      R   Pointer to cluster ID
 *                  afduLength     R   Pointer to length of data
 *                  pAfdu          R   Data array
 *
 * RETURNS:
 * NULL
 *
 ****************************************************************************/
PUBLIC bool_t JZA_bAfMsgObject(
                                APS_Addrmode_e eAddrMode,
                                uint16 u16AddrSrc,
                                uint8 u8SrcEP,
                                uint8 u8LQI,
                                uint8 u8DstEP,
                                uint8 u8ClusterID,
                                uint8 *pu8ClusterIDRsp,
                                AF_Transaction_s *puTransactionInd,
                                AF_Transaction_s *puTransactionRsp)
{
    vPrintf(E_AHI_UART_1,"receive message\r\n");
//vPrintf("message \r\n");
// if((eAddrMode==APS_ADDRMODE_SHORT)&&(u8DstEP==WSN_DATA_SINK_ENDPOINT))
  //  {
        //if(u8ClusterID==MY_CID_SENSOR_READINGS)
        //{
        /*
            u16BattVoltage=0x0000;
            u16BattVoltage=puTransactionInd->uFrame.sMsg.au8TransactionData[1];
            u16BattVoltage=u16BattVoltage<<8;
            u16BattVoltage|=puTransactionInd->uFrame.sMsg.au8TransactionData[0];

            u16XAccelerometer=0x0000;
            u16XAccelerometer=puTransactionInd->uFrame.sMsg.au8TransactionData[3];
            u16XAccelerometer=u16XAccelerometer<<8;
            u16XAccelerometer|=puTransactionInd->uFrame.sMsg.au8TransactionData[2];

            u16YAccelerometer=0x0000;
            u16YAccelerometer=puTransactionInd->uFrame.sMsg.au8TransactionData[5];
            u16YAccelerometer=u16YAccelerometer<<8;
            u16YAccelerometer|=puTransactionInd->uFrame.sMsg.au8TransactionData[4];

            u16ZAccelerometer=0x0000;
            u16ZAccelerometer=puTransactionInd->uFrame.sMsg.au8TransactionData[7];
            u16ZAccelerometer=u16ZAccelerometer<<8;
            u16ZAccelerometer|=puTransactionInd->uFrame.sMsg.au8TransactionData[6];

            u16Temperature=0x0000;
            u16Temperature=puTransactionInd->uFrame.sMsg.au8TransactionData[9];
            u16Temperature=u16Temperature<<8;
            u16Temperature|=puTransactionInd->uFrame.sMsg.au8TransactionData[8];
*/
            port3=puTransactionInd->uFrame.sMsg.au8TransactionData[7];
            port2=puTransactionInd->uFrame.sMsg.au8TransactionData[8];
            port1=puTransactionInd->uFrame.sMsg.au8TransactionData[9];
            u8IdDevice=puTransactionInd->uFrame.sMsg.au8TransactionData[10];
            u8TypeDevice=puTransactionInd->uFrame.sMsg.au8TransactionData[11];

        //}
   // }

    return (uint8) NULL;
}

/****************************************************************************
 *
 * NAME: JZA_vAfKvpResponse
 *
 * DESCRIPTION:
 * Called after a KVP transaction with acknowledgement request, when the
 * acknowledgement arrives. In this application no action is taken as no
 * KVP transaction acknowledgements are expected.
 *
 * PARAMETERS:      Name                   RW  Usage
 *                  srcAddressMod          R   Address of sender device
 *                  transactionSequenceNum R   KVP transaction number
 *                  commandTypeIdentifier  R   KVP command type
 *                  dstEndPoint            R   Endpoint at receiver
 *                  clusterID              R   Cluster ID
 *                  attributeIdentifier    R   KVP attribute ID
 *                  errorCode              R   Result code
 *                  afduLength             R   Length of payload data
 *                  pAfdu                  R   Payload data array
 *
 ****************************************************************************/
PUBLIC void JZA_vAfKvpResponse(APS_Addrmode_e eAddrMode,
                               uint16 u16AddrSrc,
                               uint8 u8SrcEP,
                               uint8 u8LQI,
                               uint8 u8DstEP,
                               uint8 u8ClusterID,
                               AF_Transaction_s *puTransactionInd)
{
        //debug code
    vPrintf(E_AHI_UART_1,"Receive ack from coordinator\n");
    //debug code
    //receive ack from coordinator
    ack=0;
    countretry = 0;
    timeout = 0;
}

/****************************************************************************
 *
 * NAME: JZA_eAfKvpObject
 *
 * DESCRIPTION:
 * Called when a KVP transaction has been received with a matching endpoint.
 *
 * PARAMETERS:      Name           RW  Usage
 *                  afSrcAddr      R   Address of sender device
 *                  u8DstEndpoint  R   Endpoint at receiver
 *                  pu8ClusterId   R   Pointer to cluster ID
 *                  eCommandTypeId R   KVP command type
 *                  u16AttributeId R   KVP attribute ID
 *                  pu8AfduLength  R   Pointer to length of data
 *                  pu8Afdu        R   Data array
 *
 * RETURNS:
 * AF_ERROR_CODE
 *
 ****************************************************************************/
PUBLIC bool_t JZA_bAfKvpObject(APS_Addrmode_e eAddrMode,
                               uint16 u16AddrSrc,
                               uint8 u8SrcEP,
                               uint8 u8LQI,
                               uint8 u8DstEP,
                               uint8 u8ClusterId,
                               uint8 *pu8ClusterIDRsp,
                               AF_Transaction_s *puTransactionInd,
                               AF_Transaction_s *puTransactionRsp)
{
    return KVP_SUCCESS;
}

/****************************************************************************
 *
 * NAME: JZA_vAppDefineTasks
 *
 * DESCRIPTION:
 * Called by Zigbee stack during initialisation to allow the application to
 * initialise any tasks that it requires. This application requires none.
 *
 * RETURNS:
 * void
 *
 ****************************************************************************/
PUBLIC void JZA_vAppDefineTasks(void)
{
}

/****************************************************************************
 *
 * NAME: JZA_vPeripheralEvent
 *
 * DESCRIPTION:
 * Called when a hardware event causes an interrupt. This function is called
 * from within the interrupt context so should be brief. In this case, the
 * information is placed on a simple FIFO queue to be processed later.
 *
 * PARAMETERS: Name          RW  Usage
 *             u32Device     R   Peripheral generating interrupt
 *             u32ItemBitmap R   Bitmap of interrupt sources within peripheral
 *
 ****************************************************************************/
PUBLIC void JZA_vPeripheralEvent(uint32 u32Device, uint32 u32ItemBitmap)
{
}

/****************************************************************************
 *
 * NAME: JZA_vAppEventHandler
 *
 * DESCRIPTION:
 * Called regularly by the task scheduler. This function reads the hardware
 * event queue and processes the events therein. It is important that this
 * function exits after a relatively short time so that the other tasks are
 * not adversely affected.
 *
 ****************************************************************************/
PUBLIC void JZA_vAppEventHandler(void)
{
    uint8 u8Msg;
    uint8 u8TimerId;

    if (!bAppTimerStarted)
    {
        //if (bNwkJoined)
        //{
            bAppTimerStarted = TRUE;
            (void)bBosCreateTimer(vAppTick, &u8Msg, 0, (APP_TICK_PERIOD_ms / 10), &u8TimerId);
       // }
    }
}

/****************************************************************************
 *
 * NAME: JZA_boAppStart
 *
 * DESCRIPTION:
 * Called by Zigbee stack during initialisation.
 *
 * RETURNS:
 * TRUE
 *
 ****************************************************************************/
PUBLIC bool_t JZA_boAppStart(void)
{
    JZS_vStartStack();
    return TRUE;
}

/****************************************************************************
 *
 * NAME: JZA_vStackEvent
 *
 * DESCRIPTION:
 * Called by Zigbee stack to pass an event up to the application.
 *
 * RETURNS:
 * TRUE
 *
 ****************************************************************************/
PUBLIC void JZA_vStackEvent(teJZS_EventIdentifier eEventId,
                            tuJZS_StackEvent *puStackEvent)
{
    if (eEventId == JZS_EVENT_NWK_JOINED_AS_ROUTER)
    {
            /* Sensor has 1 endpoint, only expects data from coordinator */

		uint8 u8InputClusterCnt      = 1;
		uint8 au8InputClusterList[]  = {WSN_CID_SENSOR_READINGS};
		uint8 u8OutputClusterCnt     = 0;
		uint8 au8OutputClusterList[] = {};

		(void)afmeAddSimpleDesc(WSN_DATA_SINK_ENDPOINT,
								WSN_PROFILE_ID,
								0x0000,
								0x00,
								0x00,
								u8InputClusterCnt,
								au8InputClusterList,
								u8OutputClusterCnt,
								au8OutputClusterList);

        bNwkJoined = TRUE;
    }
     else if (eEventId == JZS_EVENT_NETWORK_DISCOVERY_COMPLETE)
    {
        count=puStackEvent->sNetworkDiscoveryEvent.u8NetworkCount;
    }
}


PRIVATE void vTimerConfig(uint16 l, uint16 h)
{

/* set up timer 0 for PWM */
    vAHI_TimerEnable(E_AHI_TIMER_0,
                     0x00,
                     FALSE,
                     FALSE,
                     TRUE);
    vAHI_TimerClockSelect(E_AHI_TIMER_0,
                          FALSE,
                          TRUE);
    vAHI_TimerStartRepeat(E_AHI_TIMER_0,
                          l,       // low period (space)
                          h);      // period
}

PRIVATE void SET_PWM_DUTY(uint level)
{
    uint16 low=0;
    uint16 high=0;

    switch(level)
    {
        case 0:
        {
            low=PWM_CNT_H;
            high=PWM_CNT_H;
            break;
        }
        case 1:
        {
            //low=PWM_CNT_H/10;
            //low=PWM_CNT_H-low;
            low=0x7334;
            high=PWM_CNT_H;
            break;

        }
         case 2:
        {
            //low=PWM_CNT_H/20;
            //low=PWM_CNT_H-low;
            low=0x6667;
            high=PWM_CNT_H;
            break;

        }
         case 3:
        {
            //low=PWM_CNT_H/30;
            //low=PWM_CNT_H-low;
            low=0x599a;
            high=PWM_CNT_H;
            break;

        }
         case 4:
        {
            //low=PWM_CNT_H/40;
            //low=PWM_CNT_H-low;
            low=0x4ccd;
            high=PWM_CNT_H;
            break;

        }
         case 5:
        {
            //low=PWM_CNT_H/50;
            low=PWM_CNT_L;
            high=PWM_CNT_H;
            break;

        }
         case 6:
        {
            //low=PWM_CNT_H/60;
            low=0x3333;
            high=PWM_CNT_H;
            break;

        }
         case 7:
        {
            //low=PWM_CNT_H/70;
            low=0x2666;
            high=PWM_CNT_H;
            break;

        }
         case 8:
        {
            //low=PWM_CNT_H/80;
            low=0x1999;
            high=PWM_CNT_H;
            break;

        }
         case 9:
        {
            //low=PWM_CNT_H/90;
            low=0xccd;
            high=PWM_CNT_H;
            break;

        }
         case 10:
        {
            low=0;
            high=PWM_CNT_H;
            break;

        }
    }
   // vAHI_TimerStop(E_AHI_TIMER_0);
    vTimerConfig(low,high);





}
/*
PRIVATE void SET_TECNOLEDS_DIMMING(uint8 p1,uint8 p2, uint8 p3)
{

}
*/

/****************************************************************************/
/***        END OF FILE                                                   ***/
/****************************************************************************/
